/* eslint-disable */
import React, { useState, useEffect, useCallback } from 'react';
import { Table, Button, Form, Input, Modal, DatePicker, message, Select } from 'antd';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
import dayjs from 'dayjs';
import { api } from '../../services/api';
import { debounce } from 'lodash';
import './check.css'; // 引入样式文件

const { Option } = Select;

const StudentPage = () => {
  const [listData, setListData] = useState({ keyword: "", gender: "", major: "", grade: "", college: "" });
  const [tableData, setTableData] = useState([]);
  const [modalType, setModalType] = useState(0); // 0: 新增, 1: 编辑
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [form] = Form.useForm();
  const [searchForm] = Form.useForm();
  const [lastClickTime, setLastClickTime] = useState(0);
  const [isSearchTriggered, setIsSearchTriggered] = useState(false);
  const DEBOUNCE_TIME_MS = 2000; // 2秒防抖时间
  const navigate = useNavigate();

  useEffect(() => {
    getTableData(true);
  }, []);

  useEffect(() => {
    if (listData.keyword || listData.gender || listData.major || listData.grade || listData.college) {
      getTableData();
    }
  }, [listData]);

  const getToken = () => {
    return localStorage.getItem('token');
  };

  const axiosInstance = axios.create({
    baseURL: 'http://47.111.104.30:8080/api/v2/students',
    headers: {
      'Authorization': `Bearer ${getToken()}`,
      'Content-Type': 'application/json'
    }
  });

  const handleSearch = useCallback(
    debounce((val) => {
      const currentTime = Date.now();
      if (currentTime - lastClickTime < DEBOUNCE_TIME_MS) {
        message.error('您点击太快了，请稍后再试');
        return;
      }
      setLastClickTime(currentTime);

      if (val.keyword || val.gender || val.major || val.grade || val.college) {
        setListData({
          keyword: val.keyword,
          gender: val.gender,
          major: val.major,
          grade: val.grade,
          college: val.college
        });
        setIsSearchTriggered(true);
      } else {
        message.error('请输入有效的搜索条件');
      }
    }, DEBOUNCE_TIME_MS),
    [lastClickTime]
  );

  const handleClick = (type, rowData) => {
    setIsModalOpen(true);
    if (type === 'add') {
      setModalType(0);
      form.resetFields();
    } else {
      const cloneData = JSON.parse(JSON.stringify(rowData));
      cloneData.birthDate = dayjs(rowData.birthDate);
      setModalType(1);
      form.setFieldsValue(cloneData);
    }
  };

  const handleDelete = ({ id }) => {
    Modal.confirm({
      title: '确认删除',
      content: '您确认删除该学生吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        axiosInstance.delete(`/${id}`)
          .then(() => {
            message.success('删除成功');
            getTableData();
          })
          .catch(error => {
            message.error('删除失败');
            console.error('Error deleting user:', error);
          });
      }
    });
  };

  const handleCancel = () => {
    setIsModalOpen(false);
    form.resetFields();
  };

  const handleOk = useCallback(
    debounce(() => {
      const currentTime = Date.now();
      if (currentTime - lastClickTime < DEBOUNCE_TIME_MS) {
        message.error('您点击太快了，请稍后再试');
        return;
      }
      setLastClickTime(currentTime);

      form.validateFields()
        .then((val) => {
          val.birthDate = dayjs(val.birthDate).format('YYYY-MM-DD');

          const isNumberExists = tableData.some(
            student => student.number === val.number && student.id !== val.id
          );

          if (isNumberExists) {
            message.error('学号已存在，请使用其他学号');
            return;
          }

          if (modalType) {
            axiosInstance.put(`/${val.id}`, val)
              .then(() => {
                message.success('编辑成功');
                handleCancel();
                getTableData();
                // 触发学生信息更新事件
                const event = new Event('studentInfoUpdated');
                window.dispatchEvent(event);
              })
              .catch(error => {
                message.error('编辑失败');
                console.error('Error editing user:', error);
              });
          } else {
            api.post('/api/v2/students', val)
              .then(() => {
                message.success('新增成功');
                handleCancel();
                getTableData();
              })
              .catch(error => {
                message.error('新增失败');
                console.error('Error adding user:', error);
              });
          }
        })
        .catch(() => {
          Modal.error({
            title: '表单验证失败',
            content: '请确认您已经填写了所有信息',
          });
        });
    }, DEBOUNCE_TIME_MS),
    [lastClickTime, tableData, modalType]
  );

  const getTableData = (isInitialLoad = false) => {
    const { keyword, gender, major, grade, college } = listData;
    axiosInstance.get('/search', { params: { keyword, gender, major, grade, college } })
      .then(({ data }) => {
        if (!isInitialLoad && isSearchTriggered) {
          if (data.length > 0) {
            setTableData(data);
            message.success('搜索成功');
            searchForm.resetFields();
          } else {
            axiosInstance.get('/search')
              .then(({ data: allData }) => {
                setTableData(allData);
                searchForm.resetFields();
                setListData({ keyword: "", gender: "", major: "", grade: "", college: "" });
              })
              .catch(error => {
                console.error('Error fetching all data:', error);
                message.error('获取数据失败,未找到匹配的学生');
              });
          }
          setIsSearchTriggered(false);
        } else {
          setTableData(data);
        }
      })
      .catch(error => {
        message.error('搜索失败');
        console.error('Error fetching data:', error);
        axiosInstance.get('/search')
          .then(({ data: allData }) => {
            setTableData(allData);
            searchForm.resetFields();
            setListData({ keyword: "", gender: "", major: "", grade: "", college: "" });
          })
          .catch(error => {
            console.error('Error fetching all data:', error);
            message.error('获取数据失败');
          });
      });
  };

  const navigateToProfile = (student) => {
    console.log('Navigating to student profile with id:', student.id);
    navigate(`/student-profile/${student.id}`);
  };

  const columns = [
    { title: '学号', dataIndex: 'number', key: 'number' },
    { title: '姓名', dataIndex: 'name', key: 'name' },
    { title: '出生日期', dataIndex: 'birthDate', key: 'birthDate' },
    { title: '性别', dataIndex: 'gender', key: 'gender' },
    { title: '地址', dataIndex: 'address', key: 'address' },
    { title: '联系方式', dataIndex: 'phone', key: 'phone' },
    { title: '专业', dataIndex: 'major', key: 'major' },
    { title: '年级', dataIndex: 'grade', key: 'grade' },
    { title: '学院', dataIndex: 'college', key: 'college' },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => (
        <span>
          <Button style={{ marginRight: '5px' }} onClick={() => handleClick('edit', record)}>编辑</Button>
          <Button style={{ marginRight: '5px' }} type='primary' danger onClick={() => handleDelete(record)}>删除</Button>
          <Button type='primary' onClick={() => navigateToProfile(record)}>心理档案</Button>
        </span>
      ),
    },
  ];

  return (
    <div className="user">
      <div className="check flex-box space-between" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px' }}>
        <Form form={searchForm} layout="inline" onFinish={handleSearch} className="search-form">
          <Form.Item name="keyword">
            <Input placeholder="请输入学生名或学号" style={{ height: '40px' }} />
          </Form.Item>
          <Form.Item name="gender">
            <Select placeholder="请选择性别" style={{ width: 120, height: '40px' }}>
              <Option value="">全部</Option>
              <Option value="男">男</Option>
              <Option value="女">女</Option>
            </Select>
          </Form.Item>
          <Form.Item name="major">
            <Input placeholder="请输入专业" style={{ height: '40px' }} />
          </Form.Item>
          <Form.Item name="grade">
            <Input placeholder="请输入年级" style={{ height: '40px' }} />
          </Form.Item>
          <Form.Item name="college">
            <Input placeholder="请输入学院" style={{ height: '40px' }} />
          </Form.Item>
          <Form.Item>
            <Button htmlType="submit" type="primary" className="search-button">搜索</Button>
          </Form.Item>
        </Form>
        <Button type="primary" onClick={() => handleClick('add')}>+新增</Button>
      </div>
      <div style={{ marginTop: '20px', padding: '0 16px' }}>
        <Table columns={columns} dataSource={tableData} rowKey={"id"} pagination={{ pageSize: 10 }} />
      </div>
      <Modal
        open={isModalOpen}
        title={modalType ? '编辑学生' : '新增学生'}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确定"
        cancelText="取消"
      >
        <Form
          form={form}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          labelAlign="left"
        >
          {modalType === 1 && (
            <Form.Item name="id" hidden>
              <Input />
            </Form.Item>
          )}
          <Form.Item
            label="学号"
            name="number"
            rules={[
              { required: true, message: '请输入学号' },
              { pattern: /^\d+$/, message: '学号必须是数字' }
            ]}
          >
            <Input placeholder="请输入学号" />
          </Form.Item>
          <Form.Item
            label="姓名"
            name="name"
            rules={[
              { required: true, message: '请输入姓名' },
              { max: 20, message: '姓名不能超过20个字符' }
            ]}
          >
            <Input placeholder="请输入姓名" maxLength={20} />
          </Form.Item>
          <Form.Item
            label="出生日期"
            name="birthDate"
            rules={[{ required: true, message: '请选择出生日期' }]}
          >
            <DatePicker placeholder="请选择" format="YYYY-MM-DD" />
          </Form.Item>
          <Form.Item
            label="性别"
            name="gender"
            rules={[{ required: true, message: '性别是必选项' }]}
          >
            <Select
              placeholder="请选择性别"
              options={[
                { value: '男', label: '男' },
                { value: '女', label: '女' },
              ]}
            />
          </Form.Item>
          <Form.Item
            label="地址"
            name="address"
            rules={[{ required: true, message: '请填写地址' }]}
          >
            <Input placeholder="请填写地址" />
          </Form.Item>
          <Form.Item
            label="联系方式"
            name="phone"
            rules={[
              { required: true, message: '请填写联系方式' },
              { pattern: /^\d{11}$/, message: '电话号码必须是11位数字' }
            ]}
          >
            <Input placeholder="请填写联系方式" maxLength={11} />
          </Form.Item>
          <Form.Item
            label="专业"
            name="major"
            rules={[{ required: true, message: '请填写专业' }]}
          >
            <Input placeholder="请填写专业" />
          </Form.Item>
          <Form.Item
            label="年级"
            name="grade"
            rules={[{ required: true, message: '请填写年级' }]}
          >
            <Input placeholder="请填写年级" />
          </Form.Item>
          <Form.Item
            label="学院"
            name="college"
            rules={[{ required: true, message: '请填写学院' }]}
          >
            <Input placeholder="请填写学院" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default StudentPage;